package com.example.studentknowledge.repository;

import com.example.studentknowledge.entity.Follow;
import com.example.studentknowledge.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Optional;

/**
 * 关注Repository接口
 */
@Repository
public interface FollowRepository extends JpaRepository<Follow, Long> {
    
    /**
     * 根据关注者查找关注关系
     */
    Page<Follow> findByFollowerOrderByCreatedAtDesc(User follower, Pageable pageable);
    
    /**
     * 根据被关注者查找关注关系
     */
    Page<Follow> findByFollowedOrderByCreatedAtDesc(User followed, Pageable pageable);
    
    /**
     * 查找特定的关注关系
     */
    Optional<Follow> findByFollowerAndFollowed(User follower, User followed);
    
    /**
     * 检查是否存在关注关系
     */
    boolean existsByFollowerAndFollowed(User follower, User followed);
    
    /**
     * 统计用户的关注数（我关注的人数）
     */
    @Query("SELECT COUNT(f) FROM Follow f WHERE f.follower = :user")
    Long countFollowing(@Param("user") User user);
    
    /**
     * 统计用户的粉丝数（关注我的人数）
     */
    @Query("SELECT COUNT(f) FROM Follow f WHERE f.followed = :user")
    Long countFollowers(@Param("user") User user);
    
    /**
     * 获取用户关注的人列表
     */
    @Query("SELECT f.followed FROM Follow f WHERE f.follower = :user ORDER BY f.createdAt DESC")
    List<User> findFollowingUsers(@Param("user") User user, Pageable pageable);
    
    /**
     * 获取用户的粉丝列表
     */
    @Query("SELECT f.follower FROM Follow f WHERE f.followed = :user ORDER BY f.createdAt DESC")
    List<User> findFollowerUsers(@Param("user") User user, Pageable pageable);
    
    /**
     * 删除关注关系
     */
    void deleteByFollowerAndFollowed(User follower, User followed);
    
    /**
     * 删除用户的所有关注关系（作为关注者）
     */
    void deleteByFollower(User follower);
    
    /**
     * 删除用户的所有粉丝关系（作为被关注者）
     */
    void deleteByFollowed(User followed);
}